<template>
  <div class="aftersales-settings-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>售后设置</h3>
          <el-button type="primary" @click="handleSave">
            <el-icon><Check /></el-icon>
            保存设置
          </el-button>
        </div>
      </template>

      <el-tabs v-model="activeTab" type="border-card">
        <!-- 基础设置 -->
        <el-tab-pane label="基础设置" name="basic">
          <el-form :model="basicSettings" label-width="150px">
            <el-divider content-position="left">自动审核设置</el-divider>
            
            <el-form-item label="启用自动审核">
              <el-switch v-model="basicSettings.autoApprove" />
              <span class="form-tip">开启后，符合条件的售后单将自动审核通过</span>
            </el-form-item>

            <el-form-item label="自动审核金额限制" v-if="basicSettings.autoApprove">
              <el-input-number 
                v-model="basicSettings.autoApproveAmount" 
                :precision="2" 
                :min="0" 
                :step="100"
              />
              <span class="form-tip">元（单笔退款金额低于此值时自动审核）</span>
            </el-form-item>

            <el-form-item label="自动审核类型" v-if="basicSettings.autoApprove">
              <el-checkbox-group v-model="basicSettings.autoApproveTypes">
                <el-checkbox label="退货退款" />
                <el-checkbox label="仅退款" />
                <el-checkbox label="换货" />
                <el-checkbox label="维修" />
              </el-checkbox-group>
            </el-form-item>

            <el-divider content-position="left">申请时限设置</el-divider>

            <el-form-item label="售后申请期限">
              <el-input-number 
                v-model="basicSettings.applyDeadline" 
                :min="1" 
                :max="365"
              />
              <span class="form-tip">天（商品签收后可申请售后的天数）</span>
            </el-form-item>

            <el-form-item label="退货期限">
              <el-input-number 
                v-model="basicSettings.returnDeadline" 
                :min="1" 
                :max="30"
              />
              <span class="form-tip">天（审核通过后客户需在此期限内退货）</span>
            </el-form-item>

            <el-divider content-position="left">退款设置</el-divider>

            <el-form-item label="默认退款方式">
              <el-radio-group v-model="basicSettings.defaultRefundMethod">
                <el-radio label="原路退回">原路退回</el-radio>
                <el-radio label="银行转账">银行转账</el-radio>
                <el-radio label="余额退款">余额退款</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="退款处理时效">
              <el-input-number 
                v-model="basicSettings.refundDeadline" 
                :min="1" 
                :max="15"
              />
              <span class="form-tip">个工作日</span>
            </el-form-item>

            <el-divider content-position="left">其他设置</el-divider>

            <el-form-item label="启用售后评价">
              <el-switch v-model="basicSettings.enableRating" />
              <span class="form-tip">售后完成后客户可进行评价</span>
            </el-form-item>

            <el-form-item label="售后单号前缀">
              <el-input 
                v-model="basicSettings.orderNoPrefix" 
                placeholder="AS"
                style="width: 200px;"
              />
              <span class="form-tip">示例：AS202501190001</span>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 原因配置 -->
        <el-tab-pane label="原因配置" name="reason">
          <div class="reason-config">
            <div class="toolbar">
              <el-button type="primary" size="small" @click="handleAddReason">
                <el-icon><Plus /></el-icon>
                添加原因
              </el-button>
            </div>

            <el-table :data="reasonList" border stripe>
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="type" label="售后类型" width="120">
                <template #default="{ row }">
                  <el-tag :type="getTypeTagType(row.type)">{{ row.type }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="reason" label="原因" />
              <el-table-column prop="description" label="说明" show-overflow-tooltip />
              <el-table-column prop="sort" label="排序" width="80" />
              <el-table-column prop="enabled" label="状态" width="80">
                <template #default="{ row }">
                  <el-switch v-model="row.enabled" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="{ row, $index }">
                  <el-button type="primary" size="small" link @click="handleEditReason(row, $index)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" link @click="handleDeleteReason($index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 审批流程 -->
        <el-tab-pane label="审批流程" name="workflow">
          <div class="workflow-config">
            <el-alert
              title="审批流程说明"
              type="info"
              description="可根据售后类型和金额设置不同的审批流程"
              show-icon
              :closable="false"
              style="margin-bottom: 20px;"
            />

            <div class="toolbar">
              <el-button type="primary" size="small" @click="handleAddWorkflow">
                <el-icon><Plus /></el-icon>
                添加流程
              </el-button>
            </div>

            <el-table :data="workflowList" border stripe>
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="name" label="流程名称" width="150" />
              <el-table-column prop="type" label="适用类型" width="120">
                <template #default="{ row }">
                  <el-tag :type="getTypeTagType(row.type)">{{ row.type }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="amountRange" label="金额范围" width="180">
                <template #default="{ row }">
                  ¥{{ row.minAmount }} - ¥{{ row.maxAmount }}
                </template>
              </el-table-column>
              <el-table-column prop="approvers" label="审批人" show-overflow-tooltip>
                <template #default="{ row }">
                  {{ row.approvers.join(' → ') }}
                </template>
              </el-table-column>
              <el-table-column prop="enabled" label="状态" width="80">
                <template #default="{ row }">
                  <el-tag :type="row.enabled ? 'success' : 'info'">
                    {{ row.enabled ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="{ row, $index }">
                  <el-button type="primary" size="small" link @click="handleEditWorkflow(row, $index)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" link @click="handleDeleteWorkflow($index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 通知模板 -->
        <el-tab-pane label="通知模板" name="template">
          <div class="template-config">
            <el-collapse v-model="activeTemplate">
              <el-collapse-item title="售后申请通知" name="apply">
                <el-form label-width="120px">
                  <el-form-item label="启用短信通知">
                    <el-switch v-model="templates.apply.smsEnabled" />
                  </el-form-item>
                  <el-form-item label="短信模板">
                    <el-input 
                      v-model="templates.apply.smsTemplate" 
                      type="textarea" 
                      :rows="3"
                      placeholder="您的售后申请已提交，售后单号：{afterSalesNo}"
                    />
                  </el-form-item>
                  <el-form-item label="启用邮件通知">
                    <el-switch v-model="templates.apply.emailEnabled" />
                  </el-form-item>
                  <el-form-item label="邮件模板">
                    <el-input 
                      v-model="templates.apply.emailTemplate" 
                      type="textarea" 
                      :rows="5"
                    />
                  </el-form-item>
                </el-form>
              </el-collapse-item>

              <el-collapse-item title="审核通过通知" name="approve">
                <el-form label-width="120px">
                  <el-form-item label="启用短信通知">
                    <el-switch v-model="templates.approve.smsEnabled" />
                  </el-form-item>
                  <el-form-item label="短信模板">
                    <el-input 
                      v-model="templates.approve.smsTemplate" 
                      type="textarea" 
                      :rows="3"
                    />
                  </el-form-item>
                  <el-form-item label="启用邮件通知">
                    <el-switch v-model="templates.approve.emailEnabled" />
                  </el-form-item>
                  <el-form-item label="邮件模板">
                    <el-input 
                      v-model="templates.approve.emailTemplate" 
                      type="textarea" 
                      :rows="5"
                    />
                  </el-form-item>
                </el-form>
              </el-collapse-item>

              <el-collapse-item title="审核拒绝通知" name="reject">
                <el-form label-width="120px">
                  <el-form-item label="启用短信通知">
                    <el-switch v-model="templates.reject.smsEnabled" />
                  </el-form-item>
                  <el-form-item label="短信模板">
                    <el-input 
                      v-model="templates.reject.smsTemplate" 
                      type="textarea" 
                      :rows="3"
                    />
                  </el-form-item>
                  <el-form-item label="启用邮件通知">
                    <el-switch v-model="templates.reject.emailEnabled" />
                  </el-form-item>
                  <el-form-item label="邮件模板">
                    <el-input 
                      v-model="templates.reject.emailTemplate" 
                      type="textarea" 
                      :rows="5"
                    />
                  </el-form-item>
                </el-form>
              </el-collapse-item>

              <el-collapse-item title="退款完成通知" name="refund">
                <el-form label-width="120px">
                  <el-form-item label="启用短信通知">
                    <el-switch v-model="templates.refund.smsEnabled" />
                  </el-form-item>
                  <el-form-item label="短信模板">
                    <el-input 
                      v-model="templates.refund.smsTemplate" 
                      type="textarea" 
                      :rows="3"
                    />
                  </el-form-item>
                  <el-form-item label="启用邮件通知">
                    <el-switch v-model="templates.refund.emailEnabled" />
                  </el-form-item>
                  <el-form-item label="邮件模板">
                    <el-input 
                      v-model="templates.refund.emailTemplate" 
                      type="textarea" 
                      :rows="5"
                    />
                  </el-form-item>
                </el-form>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加/编辑原因对话框 -->
    <el-dialog v-model="reasonDialogVisible" :title="reasonDialogTitle" width="500px">
      <el-form :model="reasonForm" label-width="100px">
        <el-form-item label="售后类型" required>
          <el-select v-model="reasonForm.type" placeholder="请选择">
            <el-option label="退货退款" value="退货退款" />
            <el-option label="仅退款" value="仅退款" />
            <el-option label="换货" value="换货" />
            <el-option label="维修" value="维修" />
          </el-select>
        </el-form-item>
        <el-form-item label="原因" required>
          <el-input v-model="reasonForm.reason" placeholder="请输入原因" />
        </el-form-item>
        <el-form-item label="说明">
          <el-input 
            v-model="reasonForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入说明"
          />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="reasonForm.sort" :min="0" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="reasonForm.enabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reasonDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveReason">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑流程对话框 -->
    <el-dialog v-model="workflowDialogVisible" :title="workflowDialogTitle" width="600px">
      <el-form :model="workflowForm" label-width="100px">
        <el-form-item label="流程名称" required>
          <el-input v-model="workflowForm.name" placeholder="请输入流程名称" />
        </el-form-item>
        <el-form-item label="适用类型" required>
          <el-select v-model="workflowForm.type" placeholder="请选择">
            <el-option label="退货退款" value="退货退款" />
            <el-option label="仅退款" value="仅退款" />
            <el-option label="换货" value="换货" />
            <el-option label="维修" value="维修" />
            <el-option label="全部" value="全部" />
          </el-select>
        </el-form-item>
        <el-form-item label="最小金额">
          <el-input-number v-model="workflowForm.minAmount" :precision="2" :min="0" />
        </el-form-item>
        <el-form-item label="最大金额">
          <el-input-number v-model="workflowForm.maxAmount" :precision="2" :min="0" />
        </el-form-item>
        <el-form-item label="审批人" required>
          <el-select 
            v-model="workflowForm.approvers" 
            multiple 
            placeholder="请选择审批人"
            style="width: 100%;"
          >
            <el-option label="客服主管" value="客服主管" />
            <el-option label="财务主管" value="财务主管" />
            <el-option label="部门经理" value="部门经理" />
            <el-option label="总经理" value="总经理" />
          </el-select>
          <span class="form-tip">按选择顺序依次审批</span>
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="workflowForm.enabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="workflowDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveWorkflow">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, Plus } from '@element-plus/icons-vue'

// 活动标签页
const activeTab = ref('basic')

// 基础设置
const basicSettings = reactive({
  autoApprove: true,
  autoApproveAmount: 500,
  autoApproveTypes: ['仅退款'],
  applyDeadline: 7,
  returnDeadline: 7,
  defaultRefundMethod: '原路退回',
  refundDeadline: 3,
  enableRating: true,
  orderNoPrefix: 'AS'
})

// 原因列表
const reasonList = ref([
  { type: '退货退款', reason: '质量问题', description: '商品存在质量问题', sort: 1, enabled: true },
  { type: '退货退款', reason: '商品破损', description: '收到的商品有破损', sort: 2, enabled: true },
  { type: '退货退款', reason: '发错货', description: '发货与订单不符', sort: 3, enabled: true },
  { type: '仅退款', reason: '不想要了', description: '改变主意不想购买', sort: 4, enabled: true },
  { type: '换货', reason: '商品与描述不符', description: '实物与商品描述不一致', sort: 5, enabled: true },
  { type: '维修', reason: '功能故障', description: '商品功能出现故障', sort: 6, enabled: true }
])

// 审批流程列表
const workflowList = ref([
  {
    name: '普通售后流程',
    type: '全部',
    minAmount: 0,
    maxAmount: 1000,
    approvers: ['客服主管'],
    enabled: true
  },
  {
    name: '中等金额流程',
    type: '退货退款',
    minAmount: 1000,
    maxAmount: 5000,
    approvers: ['客服主管', '财务主管'],
    enabled: true
  },
  {
    name: '大额售后流程',
    type: '退货退款',
    minAmount: 5000,
    maxAmount: 999999,
    approvers: ['客服主管', '财务主管', '部门经理'],
    enabled: true
  }
])

// 通知模板
const activeTemplate = ref(['apply'])
const templates = reactive({
  apply: {
    smsEnabled: true,
    smsTemplate: '您的售后申请已提交，售后单号：{afterSalesNo}，我们会尽快处理。',
    emailEnabled: false,
    emailTemplate: ''
  },
  approve: {
    smsEnabled: true,
    smsTemplate: '您的售后申请已审核通过，请按要求退回商品。',
    emailEnabled: false,
    emailTemplate: ''
  },
  reject: {
    smsEnabled: true,
    smsTemplate: '您的售后申请未通过审核，原因：{reason}',
    emailEnabled: false,
    emailTemplate: ''
  },
  refund: {
    smsEnabled: true,
    smsTemplate: '您的退款已处理完成，金额¥{amount}将在3-5个工作日内到账。',
    emailEnabled: false,
    emailTemplate: ''
  }
})

// 原因对话框
const reasonDialogVisible = ref(false)
const reasonDialogTitle = ref('添加原因')
const reasonForm = reactive({
  type: '',
  reason: '',
  description: '',
  sort: 0,
  enabled: true
})
let reasonEditIndex = -1

// 流程对话框
const workflowDialogVisible = ref(false)
const workflowDialogTitle = ref('添加流程')
const workflowForm = reactive({
  name: '',
  type: '',
  minAmount: 0,
  maxAmount: 0,
  approvers: [],
  enabled: true
})
let workflowEditIndex = -1

// 获取类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    '退货退款': 'danger',
    '仅退款': 'warning',
    '换货': 'primary',
    '维修': 'info',
    '全部': ''
  }
  return typeMap[type] || ''
}

// 保存设置
const handleSave = () => {
  ElMessage.success('设置保存成功')
}

// 添加原因
const handleAddReason = () => {
  reasonDialogTitle.value = '添加原因'
  Object.assign(reasonForm, {
    type: '',
    reason: '',
    description: '',
    sort: 0,
    enabled: true
  })
  reasonEditIndex = -1
  reasonDialogVisible.value = true
}

// 编辑原因
const handleEditReason = (row, index) => {
  reasonDialogTitle.value = '编辑原因'
  Object.assign(reasonForm, row)
  reasonEditIndex = index
  reasonDialogVisible.value = true
}

// 保存原因
const handleSaveReason = () => {
  if (!reasonForm.type || !reasonForm.reason) {
    ElMessage.warning('请填写完整信息')
    return
  }
  
  if (reasonEditIndex >= 0) {
    Object.assign(reasonList.value[reasonEditIndex], reasonForm)
    ElMessage.success('修改成功')
  } else {
    reasonList.value.push({ ...reasonForm })
    ElMessage.success('添加成功')
  }
  
  reasonDialogVisible.value = false
}

// 删除原因
const handleDeleteReason = (index) => {
  ElMessageBox.confirm('确定要删除该原因吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    reasonList.value.splice(index, 1)
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 添加流程
const handleAddWorkflow = () => {
  workflowDialogTitle.value = '添加流程'
  Object.assign(workflowForm, {
    name: '',
    type: '',
    minAmount: 0,
    maxAmount: 0,
    approvers: [],
    enabled: true
  })
  workflowEditIndex = -1
  workflowDialogVisible.value = true
}

// 编辑流程
const handleEditWorkflow = (row, index) => {
  workflowDialogTitle.value = '编辑流程'
  Object.assign(workflowForm, row)
  workflowEditIndex = index
  workflowDialogVisible.value = true
}

// 保存流程
const handleSaveWorkflow = () => {
  if (!workflowForm.name || !workflowForm.type || workflowForm.approvers.length === 0) {
    ElMessage.warning('请填写完整信息')
    return
  }
  
  if (workflowEditIndex >= 0) {
    Object.assign(workflowList.value[workflowEditIndex], workflowForm)
    ElMessage.success('修改成功')
  } else {
    workflowList.value.push({ ...workflowForm })
    ElMessage.success('添加成功')
  }
  
  workflowDialogVisible.value = false
}

// 删除流程
const handleDeleteWorkflow = (index) => {
  ElMessageBox.confirm('确定要删除该流程吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    workflowList.value.splice(index, 1)
    ElMessage.success('删除成功')
  }).catch(() => {})
}
</script>

<style scoped>
.aftersales-settings-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.form-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

.toolbar {
  margin-bottom: 16px;
}

.reason-config,
.workflow-config,
.template-config {
  padding: 20px;
}
</style>

